﻿using System;
using System.Collections.Generic;
using System.Data.SQLite;

namespace AuriaCompte.Lib.Dao
{
    public class DaoPaiement 
        : DaoBase
    {
        public DaoPaiement()
            : base()
        {
            this.TableName = "paiements";
            this.ViewName = "paiements";
            this.PrimaryKeyName = "i_paiement_id";
            this.ListColonne.Add("i_paiement_id");
            this.ListColonne.Add("s_libelle");
        }

        public Paiement SelectById(Int32 idP)
        {
            lParam.Clear();
            Paiement retour = new Paiement();
            String req = this.DebutSelect
                + this.TableName
                + " WHERE " + this.PrimaryKeyName + " = @Id";

            lParam.Add(new SQLiteParameter("@Id", idP));

            SQLiteDataReader dr = this.ExecuteQueryReader(req, lParam);

            if (dr.Read())
                retour = ChargeFromReader(dr);
            dr.Close();
            return retour;
        }

        public List<Paiement> SelectAll()
        {
            lParam.Clear();
            List<Paiement> retour = new List<Paiement>();
            String req = this.DebutSelect
                + this.TableName;

            SQLiteDataReader dr = this.ExecuteQueryReader(req);

            while (dr.Read())
                retour.Add(ChargeFromReader(dr));
            dr.Close();
            return retour;
        }

        public Paiement Insert(Paiement p)
        {
            lParam.Clear();

            Paiement retour = new Paiement();
            String req = "INSERT INTO " + TableName + "(i_paiement_id, s_libelle) " +
                "VALUES(NULL, @s_libelle)";

            lParam.Add(new SQLiteParameter("@s_libelle", p.s_libelle));
            
            this.ExecuteNonQuery(req, lParam);
            retour = this.SelectById(Convert.ToInt32(this.LastInsertId));

            return retour;
        }

        public Paiement Update(Paiement c)
        {
            lParam.Clear();

            Paiement retour = new Paiement();
            String req = "UPDATE " + TableName + " SET s_libelle=@s_libelle " +
                " WHERE i_paiement_id=@i_paiement_id";

            lParam.Add(new SQLiteParameter("@i_paiement_id", c.i_paiement_id));
            lParam.Add(new SQLiteParameter("@s_libelle", c.s_libelle));
            
            this.ExecuteNonQuery(req, lParam);
            retour = this.SelectById(c.i_paiement_id);

            return retour;
        }

        private Paiement ChargeFromReader(SQLiteDataReader dr)
        {
            Paiement retour = new Paiement();

            retour.i_paiement_id = dr.GetInt32(0);
            if (dr.IsDBNull(1))
                retour.s_libelle = String.Empty;
            else
                retour.s_libelle = dr.GetString(1);

            return retour;
        }
    }
}
